package com.orangelife.webservice.service.paybill.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;
import com.github.pagehelper.Page;
import com.orangelife.exception.AppBizException;
import com.orangelife.other.OtherService;
import com.orangelife.redis.core.redis.session.redisSession.WebServiceSession;
import com.orangelife.service.contact.IContactService;
import com.orangelife.service.contact.modal.ContactDto;
import com.orangelife.service.feelog.IFeeLogService;
import com.orangelife.service.feelog.modal.PropFeeLogDto;
import com.orangelife.service.paybill.IPayBillService;
import com.orangelife.service.paybill.modal.PayInfo;
import com.orangelife.service.paybill.modal.Paybill;
import com.orangelife.service.propFeeComputeRule.IPropFeeComputeRuleService;
import com.orangelife.service.propFeePaybillItem.IPropFeePaybillItemService;
import com.orangelife.service.propFeePaybillItem.model.PropFeePaybillItemDto;
import com.orangelife.service.propinfo.IPropInfoService;
import com.orangelife.service.refund.IRefundService;
import com.orangelife.service.refund.modal.PropFeeRefundInfoDto;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.utils.CheckMobileAndEmail;
import com.orangelife.utils.DateUtil;
import com.orangelife.utils.IdUtil;
import com.orangelife.utils.ProConfig;
import com.orangelife.utils.PropertyUtils;
import com.orangelife.utils.StringUtils;
import com.orangelife.webservice.base.BaseService;
import com.orangelife.webservice.base.PageUtils;
import com.orangelife.webservice.service.paybill.IPayBillWebService;
import com.orangelife.webservice.service.paybill.entity.BillInfo;
import com.orangelife.webservice.service.paybill.entity.PayBillDto;
import com.orangelife.webservice.service.paybill.entity.PayBillInfo;
import com.orangelife.webservice.service.property.entity.PropComputeBean;

@Service("payBillWebService")
public class PayBillWebService extends BaseService implements
		IPayBillWebService {
	@Resource(name = "payBillService")
	private IPayBillService payBillService;
	@Resource(name = "contactService")
	private IContactService contactService;
	@Resource(name = "propInfoService")
	private IPropInfoService propInfoService;
	@Resource(name = "feeLogService")
	private IFeeLogService feeLogService;
	@Resource(name = "refundService")
	private IRefundService refundService;
	@Resource(name = "propFeePaybillItemService")
	private IPropFeePaybillItemService propFeePaybillItemService;
	@Resource(name = "propFeeComputeRuleService")
	private IPropFeeComputeRuleService propFeeComputeRuleService;

	@Override
	public Response _payBill(HttpServletRequest servletRequest,
			PayBillDto payBillDto) throws Exception {
		if (payBillDto.getCommID() == null) {
			return this.abnormalResp(100001, "小区ID不能为空");
		}
		if (payBillDto.getApartmentID() == null) {
			return this.abnormalResp(100002, "房屋ID不能为空");
		}
		if (payBillDto.getFeeDetailIDs() == null
				|| payBillDto.getFeeDetailIDs().size() == 0) {
			return this.abnormalResp(110003, "缴费ID不能为空");
		}

		// 验证缴费细项是否已经被缴

		Map<String, Object> result = new HashMap<String, Object>();
		
	
	
		boolean ispay = payBillService.checkFeeDetailIsPay(
				payBillDto.getApartmentID(), payBillDto.getFeeDetailIDs());
		if (ispay) {
			result.put("isok", 1);
			result.put("msg", " 缴费信息有变化");
			return this.normalResp(result);

		}

		// 添加缴费账单
		Map<String, Object> res = payBillService.crePayBillBack(payBillDto);

		if (res != null && "0".equals(StringUtils.toString(res.get("errCode")))) {

			String payBillID = StringUtils.toString(res.get("payBillID"));

			String payMoney = StringUtils.toString(res.get("payMoney"));
			result.put("isok", "0");
			result.put("payBillID", payBillDto.getPaybillID());
			result.put("orderID", payBillDto.getOrderID());
			result.put("newPaybillID", payBillID);
			// result.put("payMoney",payMoney);
			result.put("msg", "生成成功");
		} else {

			result.put("isok", "0");
			result.put("msg", StringUtils.toString(res.get("errInfo")));
			// return
			// this.abnormalResp(Integer.parseInt(StringUtils.toString(res.get("errCode"))),
			// StringUtils.toString(res.get("errInfo")));
		}

		return this.normalResp(result);
	}

	@Override
	public Response payNo(HttpServletRequest servletRequest, String commID,
			String payBillID) throws Exception {

		if (commID == null) {

			return this.abnormalResp(100001, "小区ID不能为空");
		}
		if (payBillID == null) {

			return this.abnormalResp(110001, "缴费账单ID不能为空");
		}

		// 获取账单信息
		Paybill paybill = payBillService.getPayBillDetail(payBillID);

		if (paybill == null) {

			return this.abnormalResp(110001, "账单信息不存在");

		}

		// 验证账单有效性；

		if (!"0".equals(paybill.getStatus()) || "1".equals(paybill.getStatus())) {

			return this.abnormalResp(1200001, "该账单不是未支付状态");

		}
		Date d = new Date();
		if (d.getTime() > paybill.getExpireTime().getTime()) {

			return this.abnormalResp(1200001, "该账单已过期");

		}

		// 验证账单细项是否有效
		// 1获取缴费细项

		List<String> feeDetailIDs = payBillService
				.getPayBillDetailIDs(payBillID);
		if (feeDetailIDs == null || feeDetailIDs.size() == 0) {

			return this.abnormalResp(1200001, "缴费细项数据异常");

		}
		boolean ispay = payBillService.checkFeeDetailIsPay(paybill
				.getApartmentID(), feeDetailIDs);
		// 1校验缴费细项有效性
		if (ispay) {

			return this.abnormalResp(1200001, "该账单缴费信息信息已变更");

		}

		// 获取支付流水号

		Map<String, String> data = new HashMap();
		data.put("payMoney", paybill.getPayMoney());
		data.put("tradeNo", paybill.getPaybillID());
		data.put("redirectUri", ProConfig.getProValues("callBackUrl"));

		// 支付中心应用ID
		data.put("appID", OtherService.appID);
		data.put("type", null);

		data.put("remark", "支付物业费");
		JSONObject jo = OtherService.addPayOrder(data);

		JSONObject res = jo.getJSONObject("entity");

		String outtradeno = (String) res.get("payOrderID");

		PropFeeLogDto log = new PropFeeLogDto();

		log.setLogID(IdUtil.getuuId());
		log.setType("1");
		log.setContentValue(paybill.getPaybillID());

		log.setContent("账单生成支付流水号：" + outtradeno);
		log.setOperation("6");
		feeLogService.addLog(log);

		Map<String, String> resmap = new HashMap<String, String>();
		resmap.put("paybillID", paybill.getPaybillID());
		resmap.put("outtradeno", outtradeno);
		resmap.put("totalCost", paybill.getPayMoney());
		resmap.put("orderContent", "物业费");
		// TODO Auto-generated method stub
		return this.normalResp(resmap);
	}

	// private Map<String,String> payNo(String commID,sTRING )
	@Override
	public Response getPayBillStatus(HttpServletRequest servletRequest,
			String commID, String payBillID) throws Exception {

		Paybill paybill = payBillService.getPayBillDetail(payBillID);

		Map<String, String> res = new HashMap<String, String>();

		res.put("status", paybill.getStatus());
		res.put("exception", paybill.getException());

		// TODO Auto-generated method stub
		return this.normalResp(res);
	}

	@Override
	public Response _payBillandPayNo(HttpServletRequest servletRequest,
			PropComputeBean propComputeBean) throws Exception {

		WebServiceSession webServiceSession = this
				.getWebServiceSession(servletRequest);
		if (webServiceSession == null) {

			return this.abnormalResp(CodeConst.SYS_CODE_2001,
					InfoConst.SYS_INFO_2001);

		}

		String memID = webServiceSession.getUserID();

		propComputeBean.setMemID(memID);
		if (propComputeBean.getCommID() == null) {

			return this.abnormalResp(100001, "小区ID不能为空");
		}

		if (propComputeBean.getApartmentID() == null) {

			return this.abnormalResp(100002, "房屋ID不能为空");
		}

		if (propComputeBean.getFeeDetailIDs() == null
				|| propComputeBean.getFeeDetailIDs().size() == 0) {

			return this.abnormalResp(110003, "缴费ID不能为空");
		}

		// 验证缴费细项是否已经被缴

		boolean ispay = payBillService.checkFeeDetailIsPay(
				propComputeBean.getApartmentID(),
				propComputeBean.getFeeDetailIDs());
		if (ispay) {

			return this.abnormalResp(110001, "有他人缴纳了该账单中的费用，请下拉页面重新加载");

		}

		// 添加缴费账单
		Map<String, Object> res = payBillService.crePayBill(propComputeBean);
		Map<String, Object> result = new HashMap<String, Object>();

		if (res != null && "0".equals(StringUtils.toString(res.get("errCode")))) {

			String payBillID = StringUtils.toString(res.get("payBillID"));

			String payMoney = StringUtils.toString(res.get("payMoney"));

			result.put("payBillID", payBillID);
			result.put("payMoney", payMoney);

			// 生成支付流水号
			Map<String, String> data = new HashMap<String, String>();
			data.put("payMoney", payMoney);
			data.put("tradeNo", payBillID);
			data.put("redirectUri", ProConfig.getProValues("callBackUrl"));
			// 支付中心应用ID
			data.put("appID", OtherService.appID);
			data.put("type", null);

			data.put("remark", "支付物业费");
			JSONObject jo = OtherService.addPayOrder(data);

			JSONObject res1 = jo.getJSONObject("entity");

			String outtradeno = (String) res1.get("payOrderID");

			PropFeeLogDto log = new PropFeeLogDto();

			log.setLogID(IdUtil.getuuId());
			log.setType("1");
			log.setContentValue(payBillID);

			log.setContent("账单生成支付流水号：" + outtradeno);
			log.setOperation("6");
			feeLogService.addLog(log);
			Map<String, String> resmap = new HashMap<String, String>();
			resmap.put("paybillID", payBillID);
			resmap.put("outtradeno", outtradeno);
			resmap.put("totalCost", payMoney);
			resmap.put("orderContent", "物业费");
			// TODO Auto-generated method stub
			return this.normalResp(resmap);

		} else {

			return this.abnormalResp(
					Integer.parseInt(StringUtils.toString(res.get("errCode"))),
					StringUtils.toString(res.get("errInfo")));
		}

	}

	@Override
	public Response paybillCallback(HttpServletRequest servletRequest)
			throws Exception {

		Map<String, Object> params = new HashMap<String, Object>();
		Enumeration<String> pNames = servletRequest.getParameterNames();
		String key = "";

		while (pNames.hasMoreElements()) {

			key = pNames.nextElement();

			params.put(key, servletRequest.getParameter(key));

		}
		String tradeNo = (String) params.get("tradeNo");
		String payOrderID = (String) params.get("payOrderID");
		String payMoney = (String) params.get("payMoney");
		String payStatus = (String) params.get("payStatus");
		String payName = (String) params.get("payName");
		String remark = (String) params.get("remark");

		if (!StringUtils.isBlank(tradeNo) && !StringUtils.isBlank(payStatus)
				&& payStatus.equals("1")) {

			PayInfo payInfo = new PayInfo();
			payInfo.setOrderID(tradeNo);
			payInfo.setTradeno(payOrderID);
			payInfo.setPayMoney(payMoney);

			payInfo.setPayName(payName);
			int n = payBillService.dealPayBill(payInfo);

			System.out.println(n);

		}

		// TODO Auto-generated method stub
		return this.normalResp();
	}

	// 获取账单详情
	@Override
	public Response openPayBill(HttpServletRequest servletRequest,
			String paybillID, String commID) throws Exception {

		Map<String, Object> payBill = payBillService
				.getPayBillDetailHasApInfo(paybillID);

		Map<String, Object> res = new HashMap<String, Object>();
		res.put("payBill", payBill);

		if (payBill == null) {
			return this.abnormalResp(120001, "账单不存在");

		}
		// 验证账单是否有效；
		String status = StringUtils.toString(payBill.get("status"));
		if ("0".equals(status) || "1".equals(status)) {

			if (payBill.get("expire_time") != null) {

				Date expireTime = (Date) (payBill.get("expire_time"));
				Date now = new Date();
				if (now.getTime() > expireTime.getTime()) {
					status = "4";
					payBill.put("status", "4");
					Paybill payBill1 = new Paybill();
					payBill1.setPaybillID(paybillID);
					payBill1.setStatus("1");
					payBillService.updatePayBill(payBill1);
				}
				;

				if ("0".equals(status)) {
					Paybill payBill1 = new Paybill();
					payBill1.setPaybillID(paybillID);
					payBill1.setStatus("1");
					payBillService.updatePayBill(payBill1);
				}

			}
		}
		List<Map<String, Object>> payBillDetails = payBillService
				.getPayBillDetails(paybillID);

		res.put("payBillDetails", payBillDetails);

		// TODO Auto-generated method stub
		return this.normalResp(res);
	}

	// 支付宝支付
	@Override
	public Response alipay(HttpServletRequest servletRequest, String commID,
			String paybillID, String type) throws Exception {
		try {
			if (commID == null) {

				return this.abnormalResp(100001, "小区ID不能为空");
			}
			if (paybillID == null) {

				return this.abnormalResp(110001, "缴费账单ID不能为空");
			}

			// 获取账单信息
			Paybill paybill = payBillService.getPayBillDetail(paybillID);

			if (paybill == null) {

				return this.abnormalResp(110001, "账单信息不存在");

			}

			Map<String, String> billstatus = new HashMap<String, String>();
			billstatus.put("2", "已支付");
			billstatus.put("3", "支付异常");
			billstatus.put("4", "已过期");
			billstatus.put("5", "已失效");
			// 验证账单有效性；

			if (!"0".equals(paybill.getStatus())
					&& !"1".equals(paybill.getStatus())) {

				return Response.ok(
						String.format(ProConfig.getProValues("tip"), "提交失败",
								billstatus.get(paybill.getStatus()), ""),
						MediaType.TEXT_HTML).build();

			}

			Date d = new Date();

			if (d.getTime() > paybill.getExpireTime().getTime()) {
				return Response.ok(
						String.format(ProConfig.getProValues("tip"), "提交失败",
								"该账单已过期", ""), MediaType.TEXT_HTML).build();

				// return this.abnormalResp(1200001, "该账单已过期");

			}

			// 验证账单细项是否有效
			// 1获取缴费细项

			List<String> feeDetailIDs = payBillService
					.getPayBillDetailIDs(paybillID);
			if (feeDetailIDs == null || feeDetailIDs.size() == 0) {

				return Response.ok(
						String.format(ProConfig.getProValues("tip"), "提交失败",
								"缴费细项数据异常", ""), MediaType.TEXT_HTML).build();

				// return this.abnormalResp(1200001, "缴费细项数据异常");

			}
			boolean ispay = payBillService.checkFeeDetailIsPay(paybill
					.getApartmentID(),  feeDetailIDs);
			// 1校验缴费细项有效性
			if (ispay) {

				paybill.setException("账单缴费信息信息已变更");
				paybill.setStatus("5");
				return Response.ok(
						String.format(ProConfig.getProValues("tip"), "提交失败",
								"该账单缴费信息信息已变更", ""), MediaType.TEXT_HTML)
						.build();

				// return this.abnormalResp(1200001, "该账单缴费信息信息已变更");

			}

			// 获取支付流水号

			Map<String, String> data = new HashMap();
			data.put("payMoney", paybill.getPayMoney());
			data.put("tradeNo", paybill.getPaybillID());
			data.put("redirectUri", ProConfig.getProValues("callBackUrl"));

			// 支付中心应用ID
			data.put("appID", OtherService.appID);
			data.put("type", null);

			data.put("remark", "支付物业费");
			JSONObject jo = OtherService.addPayOrder(data);

			JSONObject res = jo.getJSONObject("entity");

			String outtradeno = (String) res.get("payOrderID");

			PropFeeLogDto log = new PropFeeLogDto();

			log.setLogID(IdUtil.getuuId());
			log.setType("1");
			log.setContentValue(paybill.getPaybillID());

			log.setContent("账单生成支付流水号：" + outtradeno);
			log.setOperation("6");
			feeLogService.addLog(log);
			String out_trade_no = outtradeno;

			// 付款金额
			String total_fee = paybill.getPayMoney();

			// 订单名称
			// String subject =entity.getString("orderContent");

			String subject = "支付宝物业缴费";
			String payment_type = "1";
			// 必填，不能修改
			// 服务器异步通知页面路径
			String notify_url = ProConfig.getProValues("ali_notify_url");
			// 需http://格式的完整路径，不能加?id=123这类自定义参数

			// 页面跳转同步通知页面路径
			String return_url = ProConfig.getProValues("ali_return_url")
					+ "?commID=" + commID + "&paybillID=" + paybillID;
			// 需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

			// 商户网站订单系统中唯一订单号，必填

			// 商品展示地址
			String show_url = "";
			// 必填，需以http://开头的完整路径，例如：http://www.商户网址.com/myorder.html

			// 订单描述
			String body = "支付宝物业缴费";
			// 选填

			// 超时时间
			String it_b_pay = "";
			// 选填

			// 钱包token
			String extern_token = "";
			Map<String, String> sParaTemp = new HashMap<String, String>();
			sParaTemp.put("service", "alipay.wap.create.direct.pay.by.user");
			sParaTemp.put("partner", AlipayConfig.partner);
			sParaTemp.put("seller_id", AlipayConfig.seller_id);
			sParaTemp.put("_input_charset", AlipayConfig.input_charset);
			sParaTemp.put("payment_type", payment_type);
			sParaTemp.put("notify_url", notify_url);
			sParaTemp.put("return_url", return_url);
			sParaTemp.put("out_trade_no", out_trade_no);
			sParaTemp.put("subject", subject);
			sParaTemp.put("total_fee", total_fee);
			sParaTemp.put("show_url", show_url);
			sParaTemp.put("body", body);
			sParaTemp.put("it_b_pay", it_b_pay);
			sParaTemp.put("extern_token", extern_token);

			// 建立请求
			String sHtmlText = AlipaySubmit
					.buildRequest(sParaTemp, "get", "确认");

			return Response.ok(sHtmlText, MediaType.TEXT_HTML).build();
		} catch (Exception e) {

			return Response.ok(
					String.format(ProConfig.getProValues("tip"), "提交失败",
							"系统异常", ""), MediaType.TEXT_HTML).build();

		}

	}

	@Override
	public Response getContactList(HttpServletRequest servletRequest,
			String commID, String apartmentID) throws Exception {

		List<ContactDto> ll = contactService.getContactByApartmentID(
				apartmentID, null);

		// TODO Auto-generated method stub
		return this.normalResp(0, 10, 1l, ll);
	}

	@Override
	public Response sendPayBillUrl(HttpServletRequest servletRequest,

	String commID, String apartmentID, String paybillID, String contactType,
			String phone) throws Exception {

		// if(StringUtils.isBlank(phone))

		if (!CheckMobileAndEmail.isMobileT(phone)) {

			return this.abnormalResp(2002, "手机格式错误");
		}
		;

		int n = contactService.setContactByApartmentID(apartmentID,
				contactType, phone);

		Map<String, Object> m = new HashMap<String, Object>();

		List<String> mobileList = new ArrayList<String>();
		mobileList.add(phone);
		m.put("mobileList", mobileList);
		Paybill paybill = payBillService.getPayBillDetail(paybillID);
		paybill.setContactType(contactType);
		paybill.setPhone(phone);
		payBillService.updatePayBill(paybill);

		String url = ProConfig.getProValues("paybillQRcodeUrl") + "?commID="
				+ commID + "&paybillID=" + paybillID;

		// ValidateUtil.checkMobileNum(mobileNum)

		m.put("content", "【橙子生活-物业缴费】本次缴费总额：" + paybill.getPayMoney()
				+ "元，请点击链接缴费 " + url + " ");
		m.put("type", "4");
		OtherService.sendMsg(m);

		// TODO Auto-generated method stub
		return this.normalResp();
	}

	@Override
	public Response updatepaybill(String paybillId) throws AppBizException {
		if (StringUtils.isBlank(paybillId)) {
			return this.abnormalResp(100002, "账单Id不能为空");

		}

		Paybill paybill = new Paybill();
		paybill.setPaybillID(paybillId);
		paybill.setStatus("1");

		payBillService.updatePayBill2(paybill);

		return this.normalResp();
	}

	public Response _paybillPay(HttpServletRequest servletRequest,
			PayBillDto payBillDto) throws Exception {
		
		
		WebServiceSession webServiceSession = this
				.getWebServiceSession(servletRequest);
		if (webServiceSession == null) {

			return this.abnormalResp(CodeConst.SYS_CODE_2001,
					InfoConst.SYS_INFO_2001);

		}
		payBillDto.setCreateuserID(webServiceSession.getUserID());
		payBillDto.setCreateuser(webServiceSession.getRealname());
		if (StringUtils.isBlank(payBillDto.getPaybillID())) {

			return this.abnormalResp(100003, "账单ID不能为空");
		}
		if (StringUtils.isBlank(payBillDto.getCommID())) {

			return this.abnormalResp(100003, "小区ID不能为空");
		}

		if (StringUtils.isBlank(payBillDto.getApartmentID())) {

			return this.abnormalResp(100003, "房屋ID不能为空");
		}

		if (!StringUtils.isBlank(payBillDto.getRealMoney())) {	
			if (!StringUtils.isDouble(payBillDto.getRealMoney())) {

				return this.abnormalResp(100003, "实际应收金额格式错误");
			}
		
		}
		if (StringUtils.isBlank(payBillDto.getRealPay())) {	
			
			return this.abnormalResp(100003, "实收金额不能为空");
		}
		
		if (!StringUtils.isDouble(payBillDto.getRealPay())) {

			return this.abnormalResp(100003, "实收金额格式错误");
		}
	
		
		if (!StringUtils.isBlank(payBillDto.getSubMoney())) {

			if (!StringUtils.isDouble(payBillDto.getSubMoney())) {

				return this.abnormalResp(100003, "预缴付款金额格式错误");
			}

		}
		if (!StringUtils.isBlank(payBillDto.getOweMoney())) {

			if (!StringUtils.isDouble(payBillDto.getOweMoney())) {

				return this.abnormalResp(100003, "欠费金额格式错误");
			}

		}
		if (!StringUtils.isBlank(payBillDto.getPhone())) {

			if (!CheckMobileAndEmail.isMobileT(payBillDto.getPhone())) {

				return this.abnormalResp(2002, "手机格式错误");
			}
			;

		}

		
		int n = payBillService.dealPayBillOffline(payBillDto);

		Map<String, Object> res = new HashMap<String, Object>();
	
		
		if (n == -1) {

			return this.abnormalResp(100003, "预缴款金额不足");
		}

		if (n == -2) {

			return this.abnormalResp(100003, "减免金额不能大于应付金额");
		}

		if (n == 1) {

			return this.abnormalResp(100004, "账单已过期，请重新生成账单");

		} else if (n == 2) {

			return this.abnormalResp(100004, "缴费细项已产生变化，请重新生成账单");

		} else if (n == 3) {

			return this.abnormalResp(100004, "缴费账单已失效，请重新生成账单");

		} else if (n == 5) {

			return this.abnormalResp(100004, "缴费账单已失效，请重新生成账单");

		}

		// TODO Auto-generated method stub
		return this.normalResp();
	}

	@Override
	public Response _paybillErr(HttpServletRequest servletRequest,
			PropComputeBean propComputeBean) throws Exception {

		WebServiceSession webServiceSession = this
				.getWebServiceSession(servletRequest);
		if (webServiceSession == null) {

			return this.abnormalResp(CodeConst.SYS_CODE_2001,
					InfoConst.SYS_INFO_2001);

		}
		if (StringUtils.isBlank(propComputeBean.getPaybillID())) {

			return this.abnormalResp(100003, "账单ID不能为空");
		}
		if (StringUtils.isBlank(propComputeBean.getCommID())) {

			return this.abnormalResp(100003, "小区ID不能为空");
		}

		Paybill paybill = payBillService.getPayBillDetail(propComputeBean
				.getPaybillID());
		if (paybill == null) {

			return this.abnormalResp(100003, "缴费账单不存在");

		}
		paybill.setPhone(propComputeBean.getPhone());
		paybill.setExceptionstatus("2");
		paybill.setException("扫码支付已支付未到账");
		paybill.setStatus("3");
		payBillService.updatePayBill(paybill);
		PropFeeLogDto log = new PropFeeLogDto();

		log.setLogID(IdUtil.getuuId());
		log.setType("1");
		log.setContentValue(paybill.getPaybillID());

		log.setContent("后台设置为已支付未到账,操作用户ID： " + webServiceSession.getUserID()
				+ ";操作用户:" + webServiceSession.getLoginName() + ";"
				+ StringUtils.toString(webServiceSession.getTrueName(), ""));
		log.setOperation("5");
		feeLogService.addLog(log);

		// TODO Auto-generated method stub
		return this.normalResp();
	}

	@Override
	public Response _setPhoneAndInvnum(HttpServletRequest servletRequest,
			PropComputeBean propComputeBean) throws Exception {

		if (StringUtils.isBlank(propComputeBean.getPaybillID())) {

			return this.abnormalResp(100003, "账单ID不能为空");
		}
		if (StringUtils.isBlank(propComputeBean.getCommID())) {

			return this.abnormalResp(100003, "小区ID不能为空");
		}
		if (StringUtils.isBlank(propComputeBean.getApartmentID())) {

			return this.abnormalResp(100003, "房屋ID不能为空");
		}
		Paybill paybill = payBillService.getPayBillDetail(propComputeBean
				.getPaybillID());

		String invoiceNumMsg = "";

		if (!StringUtils.isBlank(propComputeBean.getInvoiceNum())) {
			paybill.setInvoiceNum(propComputeBean.getInvoiceNum());
			paybill.setInvoiceTime(new Date());

			invoiceNumMsg = "发票单号：" + propComputeBean.getInvoiceNum() + "，";

		}

		// 设置联系信息
		if (!StringUtils.isBlank(propComputeBean.getPhone())
				&& !StringUtils.isBlank(propComputeBean.getContactType())) {

			if (StringUtils.isBlank(propComputeBean.getPhone())) {

				if (!CheckMobileAndEmail.isMobileT(propComputeBean.getPhone())) {

					return this.abnormalResp(2002, "手机格式错误");
				}
				;

			}

			if (!propComputeBean.getPhone().equals(paybill.getPhone())
					|| !propComputeBean.getContactType().equals(
							paybill.getContactType())) {
				paybill.setPhone(propComputeBean.getPhone());

				contactService.setContactByApartmentID(
						propComputeBean.getApartmentID(),
						propComputeBean.getContactType(),
						propComputeBean.getPhone());

			}

		}

		payBillService.updatePayBill(paybill);

		// 验证是否发短信
		if (!StringUtils.isBlank(propComputeBean.getPhone())) {

			Map<String, Object> m = new HashMap<String, Object>();

			List<String> mobileList = new ArrayList<String>();
			mobileList.add(propComputeBean.getPhone());
			m.put("mobileList", mobileList);

			// String url
			// =ProConfig.getProValues("paybillQRcodeUrl")+"?commID="+commID+"&paybillID="+paybillID;
			String content = "【橙子生活】尊敬的业主，您于"
					+ DateUtil.DateToString(paybill.getPayTime(),
							"yyyy年MM月dd HH:mm") + " 成功缴纳物业费："
					+ paybill.getPayMoney() + "元，缴费期间："
					+ paybill.getMonthrange() + "，" + invoiceNumMsg
					+ "更多缴费详情请下载橙子生活APP http://xxxx.com";
			m.put("content", content);
			m.put("type", "4");
			OtherService.sendMsg(m);

		}

		// TODO Auto-generated method stub
		return this.normalResp();
	}

	@Override
	public Response openPayNoticeBill(HttpServletRequest servletRequest,
			String apartmentID, String commID) throws Exception {

		if (StringUtils.isBlank(commID)) {
			return this.abnormalResp(98, "小区ID不能为空");
		}
		if (StringUtils.isBlank(apartmentID)) {
			return this.abnormalResp(98, "房屋信息ID");
		}

		Map<String, Object> baseInfo = propInfoService
				.getApartmentInfo(apartmentID);
		List<Map<String, Object>> feeDetails = payBillService
				.getFeeDetailsByApartmentID(apartmentID);
		Map<String, Object> res = new HashMap<String, Object>();
		String ids = "";

		String mindate = null;
		String maxdate = null;
		BigDecimal totalAmount = new BigDecimal("0.00");
		baseInfo.put("feeDetails", feeDetails);

		for (Map<String, Object> map : feeDetails) {
			if (mindate == null) {
				mindate = StringUtils.toString(map.get("minDate"));

			} else {
				if (mindate.compareTo(StringUtils.toString(map.get("minDate"))) > 0) {

					mindate = StringUtils.toString(map.get("minDate"));
				}

			}
			if (maxdate == null) {
				maxdate = StringUtils.toString(map.get("maxDate"));

			} else {

				if (maxdate.compareTo(StringUtils.toString(map.get("maxDate"))) < 0) {

					maxdate = StringUtils.toString(map.get("maxDate"));
				}

			}
			totalAmount = totalAmount.add(new BigDecimal(StringUtils
					.toString(map.get("amount"))));
			ids += "," + StringUtils.toString(map.get("ids"));
		}

		if (mindate == null && maxdate == null) {
			baseInfo.put("monthrange", "");

		} else {

			baseInfo.put("monthrange", mindate + "至" + maxdate);
		}

		baseInfo.put("totalAmount", totalAmount);

		if (StringUtils.isBlank(ids)) {
			baseInfo.put("feeDetailIDs", "");

		} else {
			baseInfo.put("feeDetailIDs", ids.substring(1));
		}

		return this.normalResp(baseInfo);
	}

	@Override
	public Response alipay2(HttpServletRequest servletRequest, String commID,
			String apartmentID, String feeDetailIDs, String type)
			throws Exception {
		try {
			if (StringUtils.isBlank(commID)) {

				return this.abnormalResp(100001, "小区ID不能为空");
			}

			if (StringUtils.isBlank(apartmentID)) {

				return this.abnormalResp(100002, "房屋ID不能为空");
			}

			if (StringUtils.isBlank(feeDetailIDs)) {
				return Response.ok(
						String.format(ProConfig.getProValues("tip"), "提交失败",
								"无缴费信息", ""), MediaType.TEXT_HTML).build();

			}

			String[] fs = feeDetailIDs.split(",");
			// 验证缴费细项是否已经被缴

			boolean ispay = payBillService.checkFeeDetailIsPay(apartmentID,Arrays.asList(fs));
			if (ispay) {
				return Response.ok(
						String.format(ProConfig.getProValues("tip"), "提交失败",
								"缴费信息已产生变动请刷新界面", ""), MediaType.TEXT_HTML)
						.build();
				// return this.abnormalResp(110001,
				// "缴费信息已产生变动请刷新"+ProConfig.getProValues("tip"));

			}
			PropComputeBean p = new PropComputeBean();
			p.setFeeDetailIDs(Arrays.asList(fs));
			p.setApartmentID(apartmentID);
			p.setCommID(commID);
			// 添加缴费账单
			Map<String, Object> res = payBillService.crePayBill(p);
			Map<String, Object> result = new HashMap<String, Object>();

			if (res != null
					&& "0".equals(StringUtils.toString(res.get("errCode")))) {

				String payBillID = StringUtils.toString(res.get("payBillID"));

				String payMoney = StringUtils.toString(res.get("payMoney"));

				result.put("payBillID", payBillID);
				result.put("payMoney", payMoney);

				// 生成支付流水号
				Map<String, String> data = new HashMap<String, String>();
				data.put("payMoney", payMoney);
				data.put("tradeNo", payBillID);
				data.put("redirectUri", ProConfig.getProValues("callBackUrl"));
				// 支付中心应用ID
				data.put("appID", OtherService.appID);
				data.put("type", null);

				data.put("remark", "支付物业费");
				JSONObject jo = OtherService.addPayOrder(data);

				JSONObject res1 = jo.getJSONObject("entity");

				String outtradeno = (String) res1.get("payOrderID");
				PropFeeLogDto log = new PropFeeLogDto();

				log.setLogID(IdUtil.getuuId());
				log.setType("1");
				log.setContentValue(payBillID);

				log.setContent("账单生成支付流水号：" + outtradeno);
				log.setOperation("6");
				feeLogService.addLog(log);

				String out_trade_no = outtradeno;

				// 付款金额
				String total_fee = payMoney;

				// 订单名称
				// String subject =entity.getString("orderContent");

				String subject = "支付宝物业缴费";
				String payment_type = "1";
				// 必填，不能修改
				// 服务器异步通知页面路径
				String notify_url = ProConfig.getProValues("ali_notify_url");
				// 需http://格式的完整路径，不能加?id=123这类自定义参数

				// 页面跳转同步通知页面路径
				String return_url = ProConfig.getProValues("ali_return_url")
						+ "?commID=" + commID + "&paybillID=" + payBillID;
				// 需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

				// 商户网站订单系统中唯一订单号，必填

				// 商品展示地址
				String show_url = "";
				// 必填，需以http://开头的完整路径，例如：http://www.商户网址.com/myorder.html

				// 订单描述
				String body = "支付宝物业缴费";
				// 选填

				// 超时时间
				String it_b_pay = "";
				// 选填

				// 钱包token
				String extern_token = "";
				Map<String, String> sParaTemp = new HashMap<String, String>();
				sParaTemp
						.put("service", "alipay.wap.create.direct.pay.by.user");
				sParaTemp.put("partner", AlipayConfig.partner);
				sParaTemp.put("seller_id", AlipayConfig.seller_id);
				sParaTemp.put("_input_charset", AlipayConfig.input_charset);
				sParaTemp.put("payment_type", payment_type);
				sParaTemp.put("notify_url", notify_url);
				sParaTemp.put("return_url", return_url);
				sParaTemp.put("out_trade_no", out_trade_no);
				sParaTemp.put("subject", subject);
				sParaTemp.put("total_fee", total_fee);
				sParaTemp.put("show_url", show_url);
				sParaTemp.put("body", body);
				sParaTemp.put("it_b_pay", it_b_pay);
				sParaTemp.put("extern_token", extern_token);

				// 建立请求
				String sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "get",
						"确认");

				return Response.ok(sHtmlText, MediaType.TEXT_HTML).build();

			}
			return Response.ok(
					String.format(ProConfig.getProValues("tip"), " 提交失败",
							"系统异常请重新提交", ""), MediaType.TEXT_HTML).build();
		} catch (Exception e) {

			return Response.ok(
					String.format(ProConfig.getProValues("tip"), "提交失败",
							"系统异常", ""), MediaType.TEXT_HTML).build();

		}

	}

	@Override
	public Response _paybillPayForErr(HttpServletRequest servletRequest,
			PayBillInfo payBillInfo) throws Exception {

		WebServiceSession webServiceSession = this
				.getWebServiceSession(servletRequest);

		if (webServiceSession == null) {

			return this.abnormalResp(CodeConst.SYS_CODE_2001,
					InfoConst.SYS_INFO_2001);
		}
		Paybill paybill = payBillService.getPayBillDetail(payBillInfo
				.getPaybillID());

		if ("1".equals(payBillInfo.getDealType())) {

			if ("2".equals(paybill.getStatus())) {
				return this.abnormalResp(100001, "设置失败，已是已支付状态");

			}

			if (StringUtils.isBlank(payBillInfo.getPayChannel())) {

				return this.abnormalResp(100001, "支付渠道不能为空");
			}

			if (StringUtils.isBlank(payBillInfo.getTradeno())) {

				return this.abnormalResp(100001, "交易号");
			}
			List<String> feeDetailIDs = payBillService
					.getPayBillDetailIDs(payBillInfo.getPaybillID());
			if (feeDetailIDs == null || feeDetailIDs.size() == 0) {

				return this.abnormalResp(100001, "设置失败，缴费细项数据异常");

			}
			boolean ispay = payBillService.checkFeeDetailIsPay(paybill
					.getApartmentID(),  feeDetailIDs);
			// 1校验缴费细项有效性
			if (ispay) {
				return this.abnormalResp(100001, "设置失败，该账单缴费信息信息已变更");

			}
			paybill.setStatus("2");
			paybill.setPayType("3");
			paybill.setTradeno(payBillInfo.getTradeno());
			paybill.setPayChannel(payBillInfo.getPayChannel());
			// paybill.setExceptionstatus("1");

			PropFeeLogDto log = new PropFeeLogDto();

			log.setLogID(IdUtil.getuuId());
			log.setType("1");
			log.setContentValue(payBillInfo.getPaybillID());

			log.setContent("后台设置为已支付,操作用户ID： " + webServiceSession.getUserID()
					+ ";操作用户:"
					+ StringUtils.toString(webServiceSession.getTrueName(), ""));
			log.setOperation("5");
			feeLogService.addLog(log);

			payBillService.updatePayBill(paybill);

		} else if ("2".equals(payBillInfo.getDealType())) {

			paybill.setExceptionstatus("1");

			payBillService.updatePayBill(paybill);

		}

		// TODO Auto-generated method stub
		return this.normalResp();
	}

	@Override
	public Response getPayBillLog(HttpServletRequest servletRequest,
			String commID, String paybillID, String type, String operation)
			throws AppBizException {

		// TODO Auto-generated method stub
		List<PropFeeLogDto> l = feeLogService.getLogList(paybillID, type,
				operation);

		return this.normalResp(0, 1, 0l, l);
	}

	@Override
	public Response getPayBillForWeb(HttpServletRequest servletRequest,
			String commID, String status, String apartmentID, String startTime,
			String endTime, String payStartTime, String payEndTime,
			String paytime, String payType, String payChannel,
			String pageIndex, String pageSize) throws AppBizException {
		if (!StringUtils.isInt(pageIndex)) {

			return this.abnormalResp(98, "页码参数格式错误");

		}
		if (!StringUtils.isInt(pageSize)) {

			return this.abnormalResp(98, "显示条数参数格式错误");

		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("commID", commID);

		if ("6".equals(status)) {
			param.put("exceptionstatus", 2);

		} else {

			param.put("status", status);
		}
		param.put("startTime", startTime);
		param.put("endTime", endTime);
		param.put("payStartTime", payStartTime);
		param.put("payEndTime", payEndTime);
		param.put("payType", payType);
		param.put("payChannel", payChannel);
		param.put("apartmentID", apartmentID);
		param.put("pageIndex", pageIndex);
		param.put("pageSize", pageSize);
		List<Map<String, Object>> l = payBillService.getPayBill(param);

		Long total = ((Page<Map<String, Object>>) l).getTotal();
		// TODO Auto-generated method stub
		return this.normalResp(Integer.valueOf(pageIndex),
				Integer.valueOf(pageSize), total, l);
	}

	@Override
	public Response refund(HttpServletRequest servletRequest,
			PropFeeRefundInfoDto propFeeRefundInfoDto) throws AppBizException {

		refundService.addRefund(propFeeRefundInfoDto);

		// TODO Auto-generated method stub
		return this.normalResp();
	}

	@Override
	public Response _paybillDisable(HttpServletRequest servletRequest,
			PropComputeBean propComputeBean) throws Exception {
		WebServiceSession webServiceSession = this
				.getWebServiceSession(servletRequest);
		if (webServiceSession == null) {

			return this.abnormalResp(CodeConst.SYS_CODE_2001,
					InfoConst.SYS_INFO_2001);

		}
		if (StringUtils.isBlank(propComputeBean.getPaybillID())) {

			return this.abnormalResp(100003, "账单ID不能为空");
		}
		if (StringUtils.isBlank(propComputeBean.getCommID())) {

			return this.abnormalResp(100003, "小区ID不能为空");
		}

		Paybill paybill = payBillService.getPayBillDetail(propComputeBean
				.getPaybillID());
		if (paybill == null) {

			return this.abnormalResp(100003, "缴费账单不存在");

		}

		if ("2".equals(paybill.getStatus())) {

			return this.abnormalResp(100003, "该缴费账单已支付");

		}

		paybill.setStatus("5");
		payBillService.updatePayBill(paybill);
		PropFeeLogDto log = new PropFeeLogDto();

		log.setLogID(IdUtil.getuuId());
		log.setType("1");
		log.setContentValue(paybill.getPaybillID());

		log.setContent("后台设置为失效（取消扫码支付）,操作用户ID： "
				+ webServiceSession.getUserID() + ";操作用户:"
				+ webServiceSession.getLoginName() + ";"
				+ StringUtils.toString(webServiceSession.getTrueName(), ""));
		log.setOperation("5");
		feeLogService.addLog(log);

		// TODO Auto-generated method stub
		return this.normalResp();
	}

	@Override
	public Response _offlineBill(HttpServletRequest servletRequest,
			PayBillDto payBillDto) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Response getAllPropFeePaybill(HttpServletRequest servletRequest,
			Map<String, Object> payBill) throws Exception {

		String pageIndex = null;
		String pageSize = null;

		if (!payBill.containsKey("pageIndex")) {
			throw new AppBizException(2, "亲，页码大小");
		} else {
			pageIndex = payBill.get("pageIndex").toString();
		}
		if (!payBill.containsKey("pageSize")) {
			throw new AppBizException(2, "亲，页码大小");
		} else {
			pageSize = payBill.get("pageSize").toString();
		}
		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = payBillService
				.findPropFeePaybillByPage(payBill, pageUtils.getiPageIndex(),
						pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response interimPayBill(HttpServletRequest servletRequest,
			BillInfo payBill) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		int result = payBillService.addPropFeePaybill(payBill);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "添加实体成功");

		return this.normalResp();
	}

	@Override
	public Response getPayBillItems(HttpServletRequest servletRequest,
			String paybillID, String itemType, String type)
			throws AppBizException {
		
		
		List<PropFeePaybillItemDto> list=propFeePaybillItemService.findPropFeePaybillItemByRelevantID(null, paybillID, itemType, type, null);
		// TODO Auto-generated method stub
		return this.normalResp(0, 10, 0l, list);
	}

	@Override
	public Response _check(HttpServletRequest servletRequest,
			PayBillDto payBillDto) throws Exception {
		
		Map<String, Object> res = payBillService._check(payBillDto);
		// TODO Auto-generated method stub
		return this.normalResp(res);
		

	}
}
